<template>
  <div>
    <b-table
      ref="table"
      bordered
      :columns="columns"
      :out-loading="loading"
      :disabled="disabled"
      :request="loadData"
      :del-func="delFunc"
      :scroll="{ x: 1300 }"
      :export-config="{use:true,select:'管控指标明细',all:'管控指标明细'}"
      :is-show-count-bar="false"
    >
      <template slot="prefix" slot-scope="ref" v-if="!disabled">
        <a-button :loading="loadingAdd" type="primary" @click="add()">添加</a-button>
      </template>
      <template slot="suffix" slot-scope="ref">
        <a-button type="primary" @click="ref.exportHeader()">标准模板下载</a-button>
        <ExcelImportButton v-if="!disabled" @handleSubmit="importFunc" />
      </template>
      <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
      <template
        v-for="col in ['materialName','materialUnit','intoNumber','wasteNumber',
        'drawingNumber','subNumer','inControlIndex','quotaLoss','reason','remark']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <template v-if="!disabled">
            <template v-if="col === 'materialName'">
              <div style="display:flex;align-items: center;">
                <a-button style="margin-right: 10px;" @click="record.isInList = !record.isInList;record[col] = ''">
                  切换
                </a-button>
                <span class="requiredFormItem" v-if="record.isInList" style="width: 100%;">
                  <BSelect
                    :list="materialNameList"
                    v-model="record[col]"
                    @change2="save1(record)"
                  />
               </span>
                <BaseInput v-else class="requiredFormItem" v-model="record[col]" @blur="save(record)" />
              </div>
            </template>
            <BaseInputNumber
              class="requiredFormItem"
              v-if="col === 'intoNumber' ||
                col === 'wasteNumber'||
                col === 'drawingNumber'||
                col === 'subNumer'
                "
              v-model="record[col]"
              :precision="2"
              @blur="save(record)"
            />
            <BaseInput
              class="requiredFormItem"
              v-if="col === 'inControlIndex' || col === 'quotaLoss' || col === 'materialUnit'"
              v-model="record[col]"
              :precision="2"
              @blur="save(record)"
            />
            <BaseInput v-if="col === 'remark' || col === 'reason'" v-model="record[col]" @blur="save(record)" />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </b-table>
  </div>
</template>
<script>
import Api from '@/api/material/benefitAnalysis/controlIndicators.js'

export default {
  props: {
    disabled: {
      type: Boolean
    },
    id: {
      type: String
    }
  },
  data() {
    return {
      isSelectList: {},
      loading: false,
      loadingAdd: false,
      materialNameList: [
        { id: '钢筋', name: '钢筋' },
        { id: '混凝土', name: '混凝土' },
        { id: '电线', name: '电线' },
        { id: '电缆（≥25㎡，≤25㎡)', name: '电缆（≥25㎡，≤25㎡)' },
        { id: '镀锌钢管', name: '镀锌钢管' },
        { id: '焊接钢管', name: '焊接钢管' },
        { id: '无缝钢管', name: '无缝钢管' },
        { id: '桥架', name: '桥架' }
      ],
      columns: [
        { title: '序号', width: 70, scopedSlots: { customRender: 'index' } },
        { title: '物资名称', width: 300, dataIndex: 'materialName', scopedSlots: { customRender: 'materialName' } },
        // { title: '物料编码', width: 130, dataIndex: 'materialCode' },
        { title: '计量单位', width: 120, dataIndex: 'materialUnit', scopedSlots: { customRender: 'materialUnit' } },
        { title: '进场量（含调入调出）', width: 180, dataIndex: 'intoNumber', scopedSlots: { customRender: 'intoNumber' } },
        { title: '废料处理量', width: 150, dataIndex: 'wasteNumber', scopedSlots: { customRender: 'wasteNumber' } },
        { title: '图纸量', width: 150, dataIndex: 'drawingNumber', scopedSlots: { customRender: 'drawingNumber' } },
        { title: '分包结算量（不含损耗）', width: 200, dataIndex: 'subNumer', scopedSlots: { customRender: 'subNumer' } },
        { title: '损耗率', width: 150, dataIndex: 'lossRate' },
        { title: '废料率', width: 150, dataIndex: 'wasteRate' },
        { title: '内控指标', width: 150, dataIndex: 'inControlIndex', scopedSlots: { customRender: 'inControlIndex' } },
        { title: '定额损耗', width: 150, dataIndex: 'quotaLoss', scopedSlots: { customRender: 'quotaLoss' } },
        { title: '原因分析', width: 150, dataIndex: 'reason', scopedSlots: { customRender: 'reason' } },
        { title: '备注', width: 250, dataIndex: 'remark', scopedSlots: { customRender: 'remark' } }
      ],
      downloadApi: Api.downMaterialAnalysisExcel,
      delFunc: Api.deleteByDetails,
      loadData: async params => {
        let res = await Api.findListByDetails({}, Object.assign(params, { query: { controlIndicatorsId: this.id } }))
        if (res.code === this.SUCCESS_CODE) {
          res.data.map(v => {
            v.isInList = this.checkIsInList(v.materialName)
          })
          return { code: this.SUCCESS_CODE, data: res.data, ...res }
        }
        return { code: this.SUCCESS_CODE, data: [] }
      }
    }
  },
  methods: {
    checkIsInList(val) {
      return this.materialNameList.findIndex(v => v.name === val) !== -1
    },
    async importFunc(e) {
      // this.$console(e)
      let newTable = []
      let checkRes = true
      e.map(row => {
        let temp = {}
        for (const rowKey in row) {
          let column = this.columns.find(columnRow => columnRow.title === rowKey)
          if (column) {
            let dataIndex = column.dataIndex
            temp[dataIndex] = row[rowKey]
            if (checkRes && rowKey === '进场量（含调入调出）' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '废料处理量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '图纸量' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '分包结算量（不含损耗）' && typeof row[rowKey] !== 'number') checkRes = false
          }
        }
        temp.controlIndicatorsId = this.id
        newTable.push(temp)
      })
      if (!checkRes) {
        return this.$noticeWarning('数据格式错误！')
      }
      this.loading = true
      let res = await Api.createByDetailsList({}, newTable)
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        if (res.message === 'success') {
          this.$noticeSuccess('导入成功！')
          this.$refs.table.getData(null, true)
        } else {
          this.$notification.open({ message: '提示', duration: null, description: () => <pre>{res.message}</pre> })
        }
      }
    },
    async add() {
      this.loadingAdd = true
      let res = await Api.createByDetails({}, { controlIndicatorsId: this.id })
      this.loadingAdd = false
      if (res.code !== this.SUCCESS_CODE) {
        this.$noticeError('新增失败')
      } else {
        this.$refs.table.refresh()
      }
    },
    async openDialog(downloadApi) {
      let allData = []
      if (this.$refs.table.totalSize !== 0) {
        this.loadingAdd = true
        let res = await Api.findListByDetails({}, {
          pageSize: this.$refs.table.totalSize,
          pageNo: 1,
          query: { controlIndicatorsId: this.id }
        })
        this.loadingAdd = false
        if (res.code === this.SUCCESS_CODE) {
          allData = res.data
        }
      }
      if (downloadApi) {
        let fileName = '标准模板下载.xlsx'
        this.$refs.detailDialog.download(allData, downloadApi)
      } else {
        this.$refs.detailDialog.open(allData)
      }
    },
    async createList(selectRows) {
      let params = []
      selectRows.map(selectRow => {
        params.push({
          materialName: selectRow.materialName,
          materialCode: selectRow.materialCode,
          materialModel: selectRow.specificationModel,
          materialUnit: selectRow.unit,
          materialId: selectRow.id,
          controlIndicatorsId: this.id
        })
      })
      this.loading = true
      let res = await Api.createByDetailsList({}, params)
      this.loading = false
      if (res.code === 200) {
        this.$refs.table.refresh()
      }
    },
    save1(target) {
      console.log('save1')
      Api.editByByDetail({}, target).then(res => {
        if (res.code !== 200) this.$noticeWarning(res.message)
      })
    },
    save(target) {
      target.baseId = this.id
      try {
        if (
          target.intoNumber !== null
          && target.wasteNumber !== null
          && target.drawingNumber !== null
          && target.subNumer !== null
        ) {
          target.lossRate =
            (target.intoNumber -
              target.wasteNumber -
              target.subNumer)
            / target.subNumer
          target.lossRate = target.lossRate.toFixed(2)
          target.wasteRate = target.wasteNumber / target.subNumer
          target.wasteRate = target.wasteRate.toFixed(2)
        } else {
          target.lossRate = null
          target.wasteRate = null
        }
      } catch (e) {
      }
      Api.editByByDetail({}, target).then(res => {
        if (res.code !== 200) this.$noticeWarning(res.message)
      })
    }

  }
}
</script>
